/*
 * @Author: boyyang
 * @Date: 2022-01-02 00:19:39
 * @LastEditTime: 2022-02-12 12:08:04
 * @LastEditors: boyyang
 * @Description: 路由守卫
 * @FilePath: \boyyang\src\router\routerGuards.ts
 */


import { Router, RouteRecordRaw } from 'vue-router'
import { setTitle } from '@/utils/setDocumentTitle'
import { loginState } from '@/cloudbase'
import { useAsyncRoutesStoreWithOut } from '@/store/modules/asyncRoutes'
import { useUserStoreWithOut } from '@/store/modules/user'
import { asyncRoutes } from '@/router/asyncRoutes'
import { notFindRoute } from '@/router/404'

// 路由白名单
const whiteRouterList = []

const createRouterGuards = (router: Router) => {
    // 获取异步路由
    const asyncRoutesStore = useAsyncRoutesStoreWithOut()
    const userStore = useUserStoreWithOut()
    // 路由前置守卫
    router.beforeEach(async (to, from, next) => {
        // 设置当前页面title
        setTitle(to.meta.title)

        // 如果是前往登录页
        if (to.name === 'Login') {
            next()
            return
        }

        // 获取登录状态
        let state = await loginState()
        if (!state) {
            let redirect = {
                name: 'Login',
                replace: true
            }
            next(redirect)
            return
        }
        
        // 获取权限
        if (userStore.getRoles.length === 0) {
            await userStore.setRoles(['admin'])
            
            await asyncRoutesStore.setAsyncRoutes(asyncRoutes)
            // 获取通过权限验证的路由
            let routes = asyncRoutesStore.getAsyncRoutes
            routes.forEach((item) => {
                router.addRoute(item as unknown as RouteRecordRaw)
            })
            
            // 添加404
            router.addRoute(notFindRoute)

            const redirectPath = (from.query.redirect || to.path) as string
            const redirect = decodeURIComponent(redirectPath)
            const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
            next(nextData)
            return
        }

        next()
    })

    // 路由后置守卫
    router.afterEach((to, from, failure) => {

    })

    // 路由错误
    router.onError((error) => {
        console.log(
            `%c 错误： %c 路由错误  %c`,
            'background:red ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
            'background:#41b883 ; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
            'background:transparent'
        )
    })
}


export {
    createRouterGuards
}